import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { getCanvasCenter } from '../utils';

interface TextSegment {
    id: string;
    material_id: string;
    target_timerange: {
        start: number;
        duration: number;
    };
    clip: {
        alpha: number;
        scale: { x: number; y: number };
        rotation: number;
        transform: { x: number; y: number };
        flip: { horizontal: boolean; vertical: boolean };
    };
    clipSettings: {
        flip: {
            vertical: boolean;
            horizontal: boolean;
        };
        alpha: number;
        scale: {
            x: number;
            y: number;
        };
        rotation: number;
        transform: {
            x: number;
            y: number;
        };
    };
    material_info: {
        id: string;
        name: string;
        type: string;
        public_url: string | null;
        download_url: string | null;
        duration: number;
        width: number;
        height: number;
        path: string;
        original_properties: {
            id: string;
            type: string;
            content: string;
            alignment: number;
            line_feed: number;
            check_flag: number;
            typesetting: number;
            global_alpha: number;
            line_spacing: number;
            letter_spacing: number;
            line_max_width: number;
            force_apply_line_max_width: boolean;
        };
    };
    currentTrackIndex?: number; // 当前轨道层级
}

interface TextLayerProps {
    draftData: any;
    canvasWidth?: number; // 不再使用，但保留接口兼容性
    canvasHeight?: number; // 不再使用，但保留接口兼容性
}

// 判断是否为文本片段
const isTextSegment = (segment: any): boolean => {
    return segment.material_info && segment.material_info.type === 'text' && segment.material_info.original_properties && segment.material_info.original_properties.content;
};

const TextLayer: React.FC<TextLayerProps> = ({ draftData }) => {
    const [textSegments, setTextSegments] = useState<TextSegment[]>([]);

    // 防抖定时器引用
    const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

    // 从Redux获取当前时间
    const currentTime = useSelector((state: RootState) => state.timeline.currentTime);

    // 防抖更新文本片段数据
    const debouncedUpdateTextSegments = useCallback((newSegments: TextSegment[]) => {
        // 清除之前的定时器
        if (debounceTimerRef.current) {
            clearTimeout(debounceTimerRef.current);
        }

        // 设置防抖定时器
        debounceTimerRef.current = setTimeout(() => {
            setTextSegments(newSegments);
        }, 100); // 100ms 防抖延迟
    }, []);

    // 提取文本片段数据
    useEffect(() => {
        if (!draftData?.script_content?.tracks) {
            setTextSegments([]);
            return;
        }

        const tracks = draftData.script_content.tracks;
        const segments: TextSegment[] = tracks
            .filter((track: any) => track.type === 'text' && track.segments)
            .flatMap((track: any, trackIndex: number) =>
                track.segments
                    .filter((segment: any) => isTextSegment(segment))
                    .map((segment: any) => ({
                        ...segment,
                        currentTrackIndex: trackIndex,
                    }))
            )
            .map((segment: any) => ({
                id: segment.id,
                material_id: segment.material_id,
                target_timerange: segment.target_timerange,
                clip: segment.clip,
                clipSettings: segment.clipSettings,
                material_info: segment.material_info,
                currentTrackIndex: segment.currentTrackIndex,
            }));

        debouncedUpdateTextSegments(segments);
    }, [draftData, debouncedUpdateTextSegments]);

    // 组件卸载时清理定时器
    useEffect(() => {
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, []);

    // 解析文本内容
    const parseTextContent = (content: string) => {
        try {
            const parsed = JSON.parse(content);
            return {
                text: parsed.text || '',
                styles: parsed.styles || [],
            };
        } catch (error) {
            console.error('解析文本内容失败:', error);
            return {
                text: '',
                styles: [],
            };
        }
    };

    // 使用 styles 中的字号和 clipSettings 计算位置渲染文本
    const getTextStyle = (segment: TextSegment) => {
        // 根据轨道层级设置 zIndex，层级越大的显示在上层
        const zIndex = segment.currentTrackIndex || 0;
        console.log(`文本素材的zindex`, zIndex);

        // 解析文本内容
        const { styles } = parseTextContent(segment.material_info.original_properties.content);

        // 获取第一个样式的字号，如果没有则使用默认值
        const fontSize = styles.length > 0 ? styles[0].size || 16 : 16;

        // 获取文本样式
        const textStyle = styles.length > 0 ? styles[0] : {};
        const fillColor = textStyle.fill?.content?.solid?.color || [1, 1, 1]; // 默认白色
        const rgbColor = `rgb(${Math.round(fillColor[0] * 255)}, ${Math.round(fillColor[1] * 255)}, ${Math.round(fillColor[2] * 255)})`;

        // 基础样式
        const baseStyle = {
            position: 'absolute' as const,
            backgroundColor: 'transparent' as const,
            zIndex: zIndex,
            fontSize: `${fontSize * 4}px`,
            color: rgbColor,
            fontWeight: textStyle.bold ? 'bold' : 'normal',
            fontStyle: textStyle.italic ? 'italic' : 'normal',
            textDecoration: textStyle.underline ? 'underline' : 'none',
            lineHeight: 1.2,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            whiteSpace: 'nowrap' as const, // 防止换行
            width: 'fit-content', // 宽度适应内容
            minWidth: 'fit-content', // 最小宽度适应内容
            maxWidth: 'none', // 不限制最大宽度
        };
        // 只有当 clip 存在时才处理位置和变换
        if (segment.clip) {
            // 获取画布中心位置
            const canvasCenter = getCanvasCenter();
            // 根据 transform 值计算偏移量
            const offsetX = (segment.clip.transform.x || 0) * 100;
            const offsetY = (segment.clip.transform.y || 0) * 1000;

            // 计算最终位置 - 由于使用了fit-content，元素会自动居中
            const finalX = canvasCenter.x + offsetX;
            const finalY = canvasCenter.y + offsetY;

            // 构建变换字符串 - 按正确顺序应用变换
            const transforms = [];

            // 1. 先应用缩放
            if (segment.clip.scale) {
                transforms.push(`scale(${segment.clip.scale.x || 1}, ${segment.clip.scale.y || 1})`);
            }

            // 2. 再应用旋转
            if (segment.clip.rotation) {
                transforms.push(`rotate(${segment.clip.rotation}deg)`);
            }

            // 3. 最后应用翻转
            if (segment.clip.flip) {
                const scaleX = segment.clip.flip.horizontal ? -1 : 1;
                const scaleY = segment.clip.flip.vertical ? -1 : 1;
                transforms.push(`scale(${scaleX}, ${scaleY})`);
            }

            return {
                ...baseStyle,
                left: `${finalX}px`,
                top: `${finalY}px`,
                opacity: segment.clip.alpha || 1, // 使用 clip 中的 alpha 值
                transform: transforms.length > 0 ? transforms.join(' ') : undefined,
                transformOrigin: 'center center',
            };
        }

        // 没有 clip 时使用默认定位（画布中心）
        const canvasCenter = getCanvasCenter();
        return {
            ...baseStyle,
            left: `${canvasCenter.x}px`, // 减去字体大小的一半
            top: `${canvasCenter.y}px`, // 减去字体大小的一部分
            opacity: 1, // 默认完全不透明
        };
    };

    return (
        <div
            style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: 'transparent',
                zIndex: 3,
            }}
        >
            {textSegments.map((segment) => {
                // 计算是否应该显示
                const startTime = segment.target_timerange.start / 1000;
                const endTime = startTime + segment.target_timerange.duration / 1000;
                const shouldShow = currentTime >= startTime && currentTime <= endTime;

                if (!shouldShow) return null;

                const textStyle = getTextStyle(segment);
                const { text } = parseTextContent(segment.material_info.original_properties.content);

                return (
                    <div key={segment.id} style={textStyle}>
                        {text}
                    </div>
                );
            })}
        </div>
    );
};

export default TextLayer;
